package binarySearch;

import java.util.Arrays;

/**
 * @description: 二分查找边界问题
 * @author: mayunfei
 * @date: 2025/1/4 18:18
 */
public class BinarySearch {

    public static final int[] TEST_ARR = new int[]{1, 2, 3, 4, 5};
    public static final int TARGET = 3;

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        printResult(binarySearch.searchSmallerNotEquals(TEST_ARR, TARGET));
        printResult(binarySearch.searchSmallerAndEquals(TEST_ARR, TARGET));
    }

    /**
     * 第一个小于target的index
     * @param arr 待查找数组
     * @return 第一个小于target的index，不存在返回-1
     */
    public int searchSmallerNotEquals(int[] arr, int target) {
        int l = 0;
        int r = arr.length - 1;
        int index = -1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            if (arr[mid] < target) {
                l = mid + 1;
                index = mid;
            } else {
                r = mid - 1;
            }
        }
        return index;
    }

    /**
     * 第一个小于等于target的index
     * @param arr 待查找数组
     * @return 第一个小于target的index，不存在返回-1
     */
    public int searchSmallerAndEquals(int[] arr, int target) {
        int l = 0;
        int r = arr.length - 1;
        int index = -1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            if (arr[mid] <= target) {
                l = mid + 1;
                index = mid;
            } else {
                r = mid - 1;
            }
        }
        return index;
    }

    public static void printResult(int result){
        System.out.println("testArr: " + Arrays.toString(TEST_ARR));
        System.out.println("target:  " + TARGET);
        System.out.println("result:  " + result);
    }
}
